<?php
namespace App\Libs\Helper;
//require __DIR__ . '/../thirdparty/PHPMailer/PHPMailerAutoload.php';
use \App\Libs\Data\GlobalConfig;

class MailHelper extends \App\Libs\Base\Singleton
{
    protected $mailer = NULL;

    public function setSmtp($smtp) {
        $config = \App\Libs\Base\Config::instance()->mailer;
        $config = $config->{$smtp};
        $data = GlobalConfig::load();
        if (!empty($data)) {
            $mailPwds = json_decode($data['mailer_config'], TRUE);
            if ($smtp === '163') {
                $smtp = 'email_163';
            }

            $config['username'] = $mailPwds[$smtp];
            $config['password'] = $mailPwds[$smtp . '_password'];
        }
        $mail = new \PHPMailer();
        //$mail->SMTPDebug = 3;                               // Enable verbose debug output

        $mail->isSMTP();                                      // Set mailer to use SMTP
        $mail->Host = $config['host'];                         // Specify main and backup SMTP servers
        $mail->SMTPAuth = TRUE;                               // Enable SMTP authentication
        $mail->Username = $config['username'];                 // SMTP username
        $mail->Password = $config['password'];                     // SMTP password
        $mail->SMTPSecure = $config['smtp_secure'];                            // Enable TLS encryption, `ssl` also accepted
        $mail->Port = $config['port'];
        $mail->CharSet = 'utf-8';
        $mail->From = $config['username'];
        $mail->FromName = $config['username'];

        $this->mailer = $mail;

        return $this;
    }

    protected function _send($to, $subject, $content) {
        $mail = $this->mailer;
        if (is_array($to)) {
            $mail->addAddress($to['mail'], $to['name']);
        } else {
            $mail->addAddress($to);
        }

        $mail->isHTML(TRUE);

        $mail->Subject = $subject;
        $mail->Body    = $content;
        
        $status = $mail->send();

        if ( ! $status) {
            \App\Libs\Log\Logger::error('send_mail', json_encode(array(
                'smtphost' => $mail->Host,
                'from' => $mail->Username,
                'to' => $to, 'subject' => $subject, 'error' => $mail->ErrorInfo
                )
            ));
        }
        return $status;
    }

    public static function send($to, $subject, $content) {
        $smtps = array('163', 'qq', 'gmail');
        $status = FALSE;
        foreach ($smtps as $smtp) {
            $status = self::instance()->setSmtp($smtp)->_send($to, $subject, $content);
            if ($status) {
                break;
            }
        }
        if ( ! $status) {
            throw \App\Libs\Exception\RuntimeException::instance(\App\Libs\Base\Constant::MAIL_SEND_FAILED);
        }
    }
}
